package com.five.matebook.utils;

import android.content.Context;
import android.media.MediaDrm;
import android.provider.Settings;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class DeviceUtils {
    private static Context sContext;
    public static void init(Context context) {
        sContext = context;
    }
    /**
     * 获取数字版权管理设备ID
     *
     * @return WidevineID，可能为空
     */
    public static String getDeviceUuid() {
        try {
            //See https://stackoverflow.com/questions/16369818/how-to-get-crypto-scheme-uuid
            //You can find some UUIDs in the https://github.com/google/ExoPlayer source code
            final UUID WIDEVINE_UUID = new UUID(0xEDEF8BA979D64ACEL, 0xA3C827DCD51D21EDL);
            MediaDrm mediaDrm = new MediaDrm(WIDEVINE_UUID);
            byte[] widevineId = mediaDrm.getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID);
            if (widevineId == null) {
                return "";
            }
            StringBuilder sb = new StringBuilder();
            for (byte aByte : widevineId) {
                sb.append(String.format("%02x", aByte));
            }
            return calculateMD5(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Settings.System.getString(sContext.getContentResolver(), Settings.System.ANDROID_ID);
    }

    public static String calculateMD5(String input) {
        try {
            // 创建 MessageDigest 实例，指定算法为 MD5
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 将输入字符串转换为字节数组
            byte[] inputBytes = input.getBytes();

            // 使用字节数组更新摘要
            md.update(inputBytes);

            // 计算摘要
            byte[] mdBytes = md.digest();

            // 将字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte mdByte : mdBytes) {
                sb.append(Integer.toString((mdByte & 0xff) + 0x100, 16).substring(1));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

}
